require( "gip")
require( "util")

local basePath
local genPath

local failedCount
local successCount
local descFailedCount

local srcImageSuffix = ".tga"

local dstImageSuffix = ".png"

local images = {}
local imagesKeys = {}

local function saveImageToTable( image, baseX, baseY, name)
    local x, y, w, h = image.validArea()
    io.write( ".")
    local newImage = image.cut( x, y, w, h)
    if newImage == nil then
        return false
    end
    
    local v = {}
    v.image = newImage
    v.offsetX = x - baseX 
    v.offsetY = y - baseY 
    v.w = w
    v.h = h
    
    images[name] = v
    table.insert(imagesKeys, name)
    return true
end

local function dirFileCallBack( filename, isFile)
    filename = string.lower(filename)
    local dotPos = string.find( filename, srcImageSuffix, #filename - 4)
    if dotPos == nil then
        dotPos = string.find( filename, ".png", #filename - 4)
    end
    if dotPos == nil then
        return
    end
    
    local image = gip.load( filename);
    if image == nil then
        print( "\n")
        print( filename .. "load failed!")
        failedCount = failedCount + 1
        return
    end

    local name = noSuffixFileName( filename)
    local oldW = image.getW()
    local oldH = image.getH()
    io.write("-")
    if saveImageToTable( image, math.floor( oldW / 2),
        math.floor( oldH / 2), name) == true then
        successCount = successCount + 1
    end
    image = nil
end


local function picDirCallback( filename, isFile)
    if ifFile then
        return
    end
    images = {}
    imagesKeys = {}
    
    local d1Name, d2Name = splitPath( filename)

    gip.transDir( filename, dirFileCallBack, false)

    local imageCount = table.getn( imagesKeys) 
    if imageCount < 1 then
        return
    end
    table.sort( imagesKeys)

    local relPath = string.sub( d1Name, #basePath + 1)
    local newPath = genPath .. relPath
    local newPath = newPath .. d2Name .. "/"

    local descPath = newPath .. "desc.xml"
    
    gip.createParentDir( descPath)

    local descFile = io.open( descPath, "wt")
    if descFile == nil then
        print( "create desc file " .. descPaht .. " failed.")
    end

    descFile:write( '<?xml version="1.0" encoding="UTF-8" standalone="no"?>')
    descFile:write( '<r>')
    
    for _, k in ipairs(imagesKeys) do
        local v = images[k]

        local dstImagePath = newPath .. k .. dstImageSuffix

        v.image.save( dstImagePath)

        local node
        if v.offsetX == 0 and v.offsetY == 0 then
            node = string.format( '<i n="%s%s" />',
                k, dstImageSuffix)
        elseif v.offsetX == 0 then
            node = string.format( '<i n="%s%s" oy="%d" />',
                k, dstImageSuffix, v.offsetY)
        elseif v.offsetY == 0 then
            node = string.format( '<i n="%s%s" ox="%d" />',
                k, dstImageSuffix, v.offsetX)
        else
            node = string.format( '<i n="%s%s" ox="%d" oy="%d" />',
                k, dstImageSuffix, v.offsetX, v.offsetY)
        end
        descFile:write( node)
        
    end
   
    descFile:write( '</r>')
    descFile:close()
end

local function genPicDir( srcPath, dstPath)
    basePath = srcPath
    genPath = dstPath
    
    failedCount = 0
    successCount = 0
    descFailedCount = 0
    
    gip.setJpgQuality( 75)
    gip.transDir( basePath, picDirCallback, false)
    
    if failedCount == 0 and descFailedCount == 0 then
        print( "It's all OK!")
    else
        local s = string.format( "success: %d, failed: %d, desc fialed: %d",
            successCount, failedCount, descFailedCount)
        print( s)
    end
end

return function() 
    gip.init()
    genPicDir( "/export/arts/pak/picdir_src", "/export/arts/pak/picdir")
    gip.deInit()
end

